<template>
  <section class="detail">
    <HmHeader @leftClick="$router.back()">
      <template #center>
        <span class="title">面经详情</span>
      </template>
    </HmHeader>
    <div v-if="isLoading">
      <p class="loading">{{ text }}</p>
    </div>
    <div class="content" v-else>
      <header class="header">
        <h1>{{ detail.stem }}</h1>
        <p>
          {{ detail.createdAt }} | {{ detail.views }} 浏览量 |
          {{ detail.likeCount }} 点赞数
        </p>
      </header>
      <p>
        <img :src="detail.avatar" alt="" />
        <span>{{ detail.creator }}</span>
      </p>

      <main class="body">
        {{ detail.content }}
      </main>
    </div>
  </section>
</template>

<script>
import axios from "axios";
export default {
  name: "DetailsPage",
  data() {
    return {
      detail: {},
      isLoading: false,
      text: "加载中...",
      token: "",
    };
  },
  methods: {
    getDetail() {
      if (this.isLoading) return;
      if (!this.$route.params.id) {
        return;
      }
      this.isLoading = true;
      this.text = "加载中...";
      axios
        .get(
          `http://interview-api-t.itheima.net/h5/interview/show/?id=${this.$route.params.id}`,
          {
            headers: {
              Authorization: `Bearer ${this.token}`,
            },
          }
        )
        .then((res) => {
          console.log(res);
          this.isLoading = false;
          this.detail = res.data.data;
          // console.log(this.detail);
        })
        .catch((err) => {
          this.text = "加载失败";
          // this.isLoading = false;
          if (err.status === 401) {
            this.$toast("身份信息失效");
            this.$router.push("/login");
          } else {
            this.$toast("获取文章失败");
          }
        });
    },
  },
  async created() {
    this.token = localStorage.getItem("token");
    if (!this.token) {
      this.$router.push("/login");
    }
    await this.getDetail();
  },
};
</script>

<style lang="less" scoped>
.detail {
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
  .loading {
    text-align: center;
    padding: 20px;
    font-size: 16px;
    color: #999;
    height: 100%;
  }
  .content {
    padding: (10/3.75vw);
    p {
      margin-top: (10/3.75vw);
      display: flex;
      align-items: flex-end;
      img {
        width: (40/3.75vw);
        height: (40/3.75vw);
        border-radius: 50%;
        margin-right: (10/3.75vw);
      }
    }
    .body {
      margin-top: (10/3.75vw);
      text-indent: 2em;
    }
  }
}
</style>
